%% Copyright
-module(product_details_handler).
-author("").

%% API
-export([init/3, allowed_methods/2, content_types_provided/2]).
-export([get_product_details/2]).

init(_Transport, _Req, []) ->
  {upgrade, protocol, cowboy_rest}.

allowed_methods(Req, State) ->
  {[<<"GET">>], Req, State}.

content_types_provided(Req, State) ->
  {[{{<<"application">>, <<"json">>, []}, get_product_details}],
    Req, State}.

get_product_details(Req, State) ->
  case cowboy_req:binding(product_id, Req) of
    {undefined, Req1} ->
      {ok, Req2} = cowboy_req:reply(400, [], "Invalid product id", Req1),
      {ok, Req2, State};
    {ProductId, Req1} ->
      get_product_details_response(Req1, State, ProductId)
  end.

get_product_details_response(Req, State, ProductId) ->
  case cn2p_catalog:get_product_details(ProductId) of
    {ok, Product} -> {jsx:encode(Product), Req, State};
    {error, not_found} ->
      http_util:get_product_not_found_response(Req, State, ProductId)
  end.